<template>
  <section class="todoapp">
    <TodoHeader @sub="sub" />
    <TodoMain :list="showList" />
    <TodoFooter
      :list="list"
      @clear="clear"
      :type="type"
      @change="change"
      :showList="list"
    />
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todoList')) || [],
      type: 'all',
    }
  },
  methods: {
    sub(name) {
      this.list.push({
        id: this.list.length + 1,
        name,
        isDone: false,
      })
    },
    clear() {
      this.list = this.list.filter((item) => item.isDone === false)
    },
    change(type) {
      this.type = type
    },
  },
  computed: {
    showList() {
      if (this.type === 'completed') {
        // 显示已完成
        return this.list.filter((item) => item.isDone === true)
      } else if (this.type === 'active') {
        // 显示未完成
        return this.list.filter((item) => item.isDone === false)
      } else {
        return this.list // 全部显示
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('todoList', JSON.stringify(this.list))
      },
    },
  },
}
</script>

<style></style>
